<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title></title>
  <script src="/assets/js/def.js"></script>
  <script src="/hy5b/t/index.js"></script>
  <script src="/hy5b/t/frontend.js"></script>
  <link rel="stylesheet" href="/assets/lib/bootstrap/css/bootstrap.min.css" />
  <script type="text/javascript" src="/assets/lib/underscore/underscore-min.js"></script>
  <script type="text/javascript" src="/hy5b/auto/hauto.js"></script>
  <link rel="stylesheet" href="/hy5b/frontend/docs-example/docs-example.css">
  <style type="text/css">
    body, .navbar {
      width: 100vw;
      overflow-x: hidden;
    }
    .inputform h3 {
      border-bottom: 1px solid #D5D5D5;
      height: 42px;
      margin-bottom: 20px;
      position: relative;
    }

    .inputform h3 strong {
      border-bottom: 1px solid #e55;
      bottom: -1px;
      color: #666666;
      font: 16px/42px 'Microsoft YaHei', Arial, '宋体';
      height: 42px;
      left: 0;
      padding-right: 50px;
      position: absolute;
    }

    .inputform h3 .h3-tips {
      color: #ccc;
      font-size: 12px;
      font-weight: 400;
      line-height: 44px;
      margin-left: 68px;
    }

    .show-title {
      color: #999;
      font-size: 12px;
      margin-bottom: 10px;
      word-break: break-all;
    }

    .btn-separate .btn + .btn {
      margin-left: 3px;
    }
  </style>
</head>

<body class="noflowX">
  <div class="navbar navbar-default navbar-fixed-top">
    <div class="container">
      <div class="navbar-form">
        <div class="form-group">
          <label>select</label>
          <select name="request_code" class="form-control" id="request_code"></select>
        </div>
        <button class="btn" id="create">Create</button>
      </div>
    </div>
  </div>

  <script type="text/javascript">

    (function () {
      //code
      var adata = [{
        action: 'test',
        url: 'request.js',
        param: {
          a: "aa",
          b: "bbb"
        }
      }, {
        action: 'getData',
        url: 'http://localhost:7700/report/edit/api/dataset/getPageByData?datasource=other&datasetId=8ea2653c90c74768ab40c494c545a582&page=1&pageSize=5',
        param: { "aggFieldOps": [], "groupByFields": ["resource", "system.cpu.pct_usage"], "condition": { "logic": "AND", "items": [], "nestedConditions": [] }, "pageBy": ["resource"], "filter": { "time": { "recent": { "display": "recent 1 months", "value": "43200" } }, "resourceClass": ["VM"], "target": ["system.cpu.pct_usage"] } }
      }, {
        action: 'mailapi',
        url: 'https://mailapi.kyoko.finance/api/sns/message',
        param: {}
      }, {
        action: 'snsapi',
        url: 'https://snsapi.kyoko.finance/api/sns/message',
        param: {}
      }];

      $.each(adata, function (index, data) {
        $("#request_code").append('<option value="' + index + '">' + data.action + '</option>');
      });

      function create() {
        var i = document.getElementById("request_code").value;

        var url = adata[i].url;
        var param = adata[i].param;
        layoutForm(url, adata[i]);
      }

      $("#create").click(create)

    }());


    function layoutForm(url, options) {
      var className = "example-" + parseInt(Math.random() * 10000);
      $('head').eq(0).append('<style>.' + className + '::after {content:"' + options.action + '";}');

      ajaxForm(url, options)
        .init(function ($dform, $dajax, $dresult) {
          $('<div class="row" style="padding-top: 60px;">')
            .append($('<div class="col-md-3">')
              .append($('<div class="docs-example">').addClass(className).append($dform)))
            .append($('<div class="col-md-3">')
              .append($('<div class="docs-example">').append($dajax)))
            .append($('<div class="col-md-6">')
              .append($('<div class="docs-preview">').append($dresult)))
            .appendTo('body');
        })
        .submit();
    }

    function jsonLize(param) {
      if (t.isObject(param) || t.isArray(param)) {
        return JSON.stringify(param, null, 2);
      } else {
        return param;
      }
    }


    function ajaxForm(url, options) {

      url = url || "#";

      var contentType = '';

      var signature = Math.random();

      var name = "form_" + signature;

      var target = options.target || "target_" + signature;

      var $dformWrap = $('<div class="inputform">')
        .append(
          $('<div class="form-group">')
            .append('<label>url</label>')
            .append($('<input class="form-control" id="url_'+ signature + '">').val(url))
        )
        .append(
          $('<div class="form-group">')
            .append('<label>contentType</label>')
            .append(
              $('<select class="form-control" id="contentType_'+ signature + '">')
                .append('<Option value="application/x-www-form-urlencoded" selected>application/x-www-form-urlencoded</Option>')
                .append('<Option value="multipart/form-data">multipart/form-data</Option>')
                .append('<Option value="text/plain">text/plain</Option>')
                .append('<Option value="application/json">application/json</Option>')
            )
        )
        .append(
          $('<div class="form-group">')
            .append($('<button class="btn btn-default">Reset</button>').click(resetUrl))
        )
      
      var $dform = $('<form class="inputform" method="POST" name="' + name + '" target="' + target + '" action="' + url + '"></form>').appendTo($dformWrap);

      $dform.append('<h3>'
        + '<strong>FORM-T</strong>'
        + '<span class="h3-tips">pd by ajax.exe - a test form</span>'
        + '</h3>'
      )

      $dform.append('<div class="show-title">POST <span class="url-title">' + url + '</span></div>');
      $dform.append('<div class="show-title">enctype: <span class="contentType-title">' + contentType + '</span></div>');

      $dformInput = $('<div>').appendTo($dform);

      setFormInputs($dformInput, options.param || {});

      $dform.append(
        $('<div class="form-group">')
          .append($('<button class="btn btn-default">Submit</button>').click(formSubmit))
      );

      var $diframe = $('<iframe name="' + target + '" src="about:blank"></iframe>');

      var $dajaxDataType = $('<select class="form-control" multiple>')
        .append('<Option value="json" selected>json</Option>')
        .append('<Option value="jsonp">jsonp</Option>')
        .append('<Option value="text">text</Option>')
        .append('<Option value="html">html</Option>')
        .append('<Option value="script">script</Option>')
        .append('<Option value="xml">xml</Option>');

      var $dajaxParam = $('<textarea class="form-control fixed-regular scrollbar-adjust-radius" rows="4">').val(JSON.stringify(options.param, null, 2));
      var $dajaxSettings = $('<textarea class="form-control fixed-regular scrollbar-adjust-radius" rows="3">');
      var $dajax = $('<div>')
        .append($('<div class="form-group">').append('<label>dataType</label>').append($dajaxDataType))
        .append($('<div class="form-group">').append('<label>params/data</label>').append($dajaxParam))
        .append($('<div class="form-group">').append('<label>settings</label>').append($dajaxSettings))
        .append($('<div class="form-group btn-separate">')
          .append($('<button class="btn">← Reset</button>').click(resetOption))
          .append($('<button class="btn">GET</button>').click(ajaxGet))
          .append($('<button class="btn">POST</button>').click(ajaxPost)));

      var $dajaxReturn = $('<div>');

      var $dresult = $('<div>').append($diframe).append($dajaxReturn);
      var initialized = false;

      function setFormInputs($elem, data) {
        for (var param in data) {
          if (t.isArray(data[param])) {
            for (var i = 0; i < data[param].length; i++) {
              $('<div class="form-group">')
                .append('<label>' + param + '</label>')
                .append($('<input class="form-control" name="' + param + '">').val(jsonLize(data[param][i])))
                .appendTo($elem);
            }
          } else {
            $('<div class="form-group">')
              .append('<label>' + param + '</label>')
              .append($('<input class="form-control" name="' + param + '">').val(jsonLize(data[param])))
              .appendTo($elem);
          }
        }
      }

      function resetUrl() {
        url = document.getElementById('url_' + signature).value || url;
        contentType = document.getElementById('contentType_' + signature).value || contentType;
        $dform.attr('action', url).attr('enctype', contentType);
        $dform.find('.url-title').html(url);
        $dform.find('.contentType-title').html(contentType);
      }

      function resetOption() {
        var param = $dajaxParam.val();
        try {
          param = JSON.parse(param)
        } catch (e) {
          param = {}
        }

        $dformInput.empty();
        setFormInputs($dformInput, param);
      }

      function ajaxGet(e) {
        $diframe.hide()
        $dajaxReturn.empty();
        $dajaxReturn.show();

        var param = $dajaxParam.val()
        try {
          param = JSON.parse(param)
        } catch (e) {
          param = {}
        }

        var dataType = $dajaxDataType.val();

        $.get(url, param, function (data) {
          $dajaxReturn.html(jsonLize(data))
        }, dataType)
      }

      function ajaxPost(e) {
        $diframe.hide();
        $dajaxReturn.empty();
        $dajaxReturn.show();

        var param = $dajaxParam.val() || "{}";
        var settings = $dajaxSettings.val() || "{}";
        try {
          param = JSON.parse(param)
          settings = JSON.parse(settings);
        } catch (e) {
          param = {};
          settings = {};
          console.error(e);
        }

        var dataType = $dajaxDataType.val();

        $.ajax({ //这种复杂的setting用$.post是无效的
          url: url,
          method: 'POST',
          dataType: dataType || undefined,
          contentType: contentType || undefined,
          data: contentType === 'application/json' ? JSON.stringify(param) : param,
          ...settings,
          success: function (data) {
            $dajaxReturn.html(jsonLize(data))
          }
        })
      }

      function formSubmit() {
        $dajaxReturn.hide();
        $diframe.show();

        $dform.submit();
      }

      return {
        submit: function () {
          // formSubmit();
          return this;
        },
        init: function (call) {
          call($dformWrap, $dajax, $dresult);
          initialized = true;
          return this;
        }
      }
    }

  </script>
</body>

</html>